package com.springboot.Controller;
import com.springboot.Service.UserService;
import com.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

/**
 * Created by
 * 白夜行 on 2018/5/9.
 */
@Controller
public class HelloController {

    @Autowired
    UserService userService;


    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView=new ModelAndView();
        List<User> userList = userService.getUser();
        modelAndView.setViewName("index");
        modelAndView.addObject("userList",userList);
        return modelAndView;
    }

    @RequestMapping("/toAdd")
    public String toAddUser(){
        return "add";
    }

    @RequestMapping("/add")
    public ModelAndView addUser(User user){
        ModelAndView modelAndView  = new ModelAndView();
        int isAdd = userService.addUser(user);
        if (isAdd>0) {
            modelAndView.setViewName("redirect:index?isAdd=yes");
        }else{
            modelAndView.setViewName("redirect:index?isAdd=false");
        }
        return modelAndView;
    }

    @RequestMapping("/del")
    public ModelAndView delUser(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        int isDel = userService.delUser(id);
        if (isDel>0) {
            modelAndView.setViewName("redirect:index?isDel=yes");
        }else{
            modelAndView.setViewName("redirect:index?isDel=false");
        }
        return modelAndView;
    }

    @RequestMapping("/getUser")
    public ModelAndView getUser(Integer id){
        ModelAndView modelAndView  = new ModelAndView();
        User user = userService.getUserById(id);
        modelAndView.addObject("user",user);
        modelAndView.setViewName("update");
        return modelAndView;
    }

    @RequestMapping("/updateUser")
    public ModelAndView updateUser(User user){
        ModelAndView modelAndView = new ModelAndView();
        int isUpdate = userService.UpdateUser(user);
        if (isUpdate>0) {
            modelAndView.setViewName("redirect:index?isUpdate=yes");
        }else{
            modelAndView.setViewName("redirect:index?isUpdate=false");
        }
        return modelAndView;
    }
}
